<?php

/**
 * @Author: king
 * @Date:   2019-05-04 16:31:17
 * @Last Modified by:   king
 * @Last Modified time: 2019-06-07 13:57:24
 */
namespace App\Models\Api;
use App\Exceptions\ApiException;
use App\Models\Api\Base;
use AstroTool\cache\CacheManage;
use Cache;

class LanmeiCommentTag extends Base
{
    protected $table = 'comment_tag';

    /**
     * 通过数据库 统计咨询师--点评标签
     * @param $cid
     * @return array
     */
    protected static function counselorCommentStatistics($cid)
    {   // 统计 用户点评
        $data = self::where('c_id', $cid)
                ->groupBy('cac_id')
                ->orderBy('num', 'desc')
                ->limit(5)
                ->select('cac_id', \DB::raw('COUNT(*) as num'))
                ->get()->toArray();
        // 获取标签ID
        $data = json_encode($data);
        return $data;
    }

    /**
     * 获取 咨询师 用户点评
     * @param $cid
     * @return array
     * @throws \Exception
     */
    public static function getCounselorComment($cid)
    {   // 获取--咨询师 用户点评
        $data = CacheManage::getInstance()
            ->setCacheConfig('counselor_comment_tag', $cid)
            ->getDataAndSet(function () use ($cid)
            {
                return self::counselorCommentStatistics($cid);
            });

        $data = json_decode($data, true);
        $tagData = LanmeiTag::getTagData(2);

        $commentData = [];
        foreach ($data as $key=>$tid)
        {
            $commentData[$tid['cac_id']] = $tagData[$tid['cac_id']];
        }

        return $commentData;
    }

    /**
     * 更新 咨询师--用户点评
     * @param $cid
     * @return bool
     * @throws \Exception
     */
    public static function updateCounselorComment($cid)
    {   // 获取咨询师--用户点评
        $data = self::counselorCommentStatistics($cid);
        // 更新缓存
        CacheManage::getInstance()->setCacheConfig('counselor_comment_tag', $cid)->setCache($data, 'details', false);

        return true;
    }
}